using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ERP.HumanResources.HumanResourceManagement;
using ERP.HumanResources.HumanResourceManagement.Dtos;
using ERP.RBAC;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using Microsoft.Extensions.Logging;

namespace ERP.Web.Controllers
{
    public class PositionLevelController : Controller
    {
        private readonly IPositionLevelService _positionLevelService;
        private readonly IMenuServices _menuServices;
        private readonly ILogger<PositionLevelController> _logger;

        public PositionLevelController(
            IPositionLevelService positionLevelService, 
            IMenuServices menuServices,
            ILogger<PositionLevelController> logger)
        {
            _positionLevelService = positionLevelService;
            _menuServices = menuServices;
            _logger = logger;
        }

        /// <summary>
        /// 职级管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 职级添加/编辑页面
        /// </summary>
        public IActionResult AddEdit()
        {
            return View();
        }

        /// <summary>
        /// 获取职级列表数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPositionLevels(GetPositionLevelInputDto input)
        {
            try
            {
                _logger.LogInformation("获取职级列表，参数: {@Input}", input);
                var result = await _positionLevelService.GetListAsync(input);
                
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取职级列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<PositionLevelDto>()
                });
            }
        }

        /// <summary>
        /// 获取职级详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPositionLevel(int id)
        {
            try
            {
                _logger.LogInformation("获取职级详情，ID: {Id}", id);
                var result = await _positionLevelService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取职级详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成职级编号
        /// </summary>
        [HttpGet]
        public IActionResult GenerateJobGradeCoding()
        {
            try
            {
                // 生成职级编号：PL + 年月日时分秒
                string code = "PL" + DateTime.Now.ToString("yyyyMMddHHmmss");
                _logger.LogInformation("生成职级编号: {Code}", code);
                return Json(new { success = true, code = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成职级编号失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建职级
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreatePositionLevel(CreatePositionLevelDto input)
        {
            _logger.LogInformation("创建职级，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("创建职级参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _positionLevelService.CreateAsync(input);
                _logger.LogInformation("创建职级成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建职级失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新职级
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdatePositionLevel(UpdatePositionLevelDto input)
        {
            _logger.LogInformation("更新职级，参数: {@Input}", input);
            
            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新职级参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var id = input.Id;
                var result = await _positionLevelService.UpdateAsync(id, input);
                _logger.LogInformation("更新职级成功，ID: {Id}", id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新职级失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除职级
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeletePositionLevel(DeletePositionLevelDto input)
        {
            _logger.LogInformation("删除职级，ID: {Id}", input.Id);
            
            try
            {
                await _positionLevelService.DeleteAsync(input.Id);
                _logger.LogInformation("删除职级成功，ID: {Id}", input.Id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除职级失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除职级
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDeletePositionLevels(BatchDeletePositionLevelsDto input)
        {
            _logger.LogInformation("批量删除职级，IDs: {@Ids}", input.Ids);
            
            try
            {
                await _positionLevelService.BatchDeleteAsync(input.Ids);
                _logger.LogInformation("批量删除职级成功，数量: {Count}", input.Ids.Count);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除职级失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 导出职级
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> ExportPositionLevels(GetPositionLevelInputDto input)
        {
            _logger.LogInformation("导出职级，参数: {@Input}", input);
            
            try
            {
                var fileBytes = await _positionLevelService.ExportAsync(input);
                _logger.LogInformation("导出职级成功，文件大小: {Size}KB", fileBytes.Length / 1024);
                return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "职级管理数据.xlsx");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出职级失败");
                return Json(new { success = false, message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 用于删除请求的DTO
    /// </summary>
    public class DeletePositionLevelDto
    {
        public int Id { get; set; }
    }

    /// <summary>
    /// 用于批量删除请求的DTO
    /// </summary>
    public class BatchDeletePositionLevelsDto
    {
        public List<int> Ids { get; set; } = new List<int>();
    }
} 